<?php

namespace App\V3\V3_2\Models;

use DateTimeInterface;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class StorageModel extends Model
{
    use HasFactory;

    protected $table = 'storage';
    protected $dateFormat = 'U';//这个时间字段被为被格式化为UNIX 时间戳的形式存储

    //toArray 时间转换问题
    public static function createDefaultProductStorage($mainUserId)
    {
        return self::insertGetId([
            'storage_name' => '默认成品库',
            'storage_address' => '默认成品库',
            'is_product_storage' => 1,
            'user_id' => $mainUserId,
            'remarks' => '',
            'main_id' => $mainUserId,
            'created_at' => time()
        ]);
    }

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    //仓库列表
    static public function getStorageList($parentId, $data)
    {
        return self::select(
            'a.id',
            'a.storage_name',
            'a.storage_address',
            'a.user_id',
            'a.remarks',
            'b.nickname', 'b.username'
        )
            ->from('storage as a')
            ->leftJoin('admin as b', 'b.id', '=', 'a.user_id')
            ->where($parentId)
//            ->where('a.is_product_storage', 0)
            ->where('a.delete_flag', 0)
            ->where(function($query) use ($data) {
                $query->orWhere('storage_name', 'like', '%'.$data['keyword'].'%');
                $query->orWhere('storage_address', 'like', '%'.$data['keyword'].'%');
            })
            ->orderBy('a.id', 'DESC')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage'])->toArray();
    }

    static public function getStorageSelect($userId)
    {

        return self::select(
            'id',
            'storage_name',
            'storage_address'
        )
            ->where($userId)
            ->where('delete_flag', 0)
            ->orderBy('id', 'DESC')
            ->get();
    }

    //获取指定仓库信息
    static public function getStorageInfo($storageName, $storageId, $mainId)
    {
        return self::where([
            'storage_name' => $storageName,
            'id' => $storageId,
            'main_id' => $mainId,
            'delete_flag' => 0,
        ])->first();
    }

    public static function getStorageDetail($storageId)
    {
        return self::where([
            'id' => $storageId,
            'delete_flag' => 0,
        ])->first();
    }

    public function shelfList()
    {
        return self::hasMany(StorageShelfModel::class, 'storage_id', 'id');
    }
}
